import {createRouter, createWebHashHistory} from "vue-router";
import auth from "@/utils/auth";

import Order from "@/components/order/Order.vue";
import Mine from "@/components/Mine.vue";
import Home from "@/components/Home.vue";
import merchant from "@/components/merchant/Merchant.vue";
import SubmitOrder from "@/components/merchant/SubmitOrder.vue";
import FYAddressList from "@/components/common/FYAddressList.vue";
import FVAddressEdit from "@/components/common/FVAddressEdit.vue";
import Login from "@/components/Login.vue";

// 2. 定义一些路由
const routes = [
    { path: '/', component: Home ,name: 'main'},
    { path: '/order', component: Order, name: 'order'},
    { path: '/mine', component: Mine, name: 'mine'},
    { path: '/merchant/:merchant_id', component: merchant, name: 'merchant'},
    { path: '/submitorder', component: SubmitOrder, name: 'submitorder'},
    { path: '/address', component: FYAddressList, name: 'address_list'},
    { path: '/address/edit', component: FVAddressEdit, name: 'address_edit'},
    { path: '/address/add', component: FVAddressEdit, name: 'address_add'},
    { path: '/login', component: Login, name: 'login'}
]

// 3. 创建路由实例并传递 `routes` 配置
const router = createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    history: createWebHashHistory(),
    routes: routes, // `routes: routes` 的缩写
})

// 注册一个全局前置守卫
router.beforeEach((to, from, next) => {
    // console.log(auth.token)
    if (to.name === "login"){
        next() // 放行
    }
    if(auth.token === null) {    //判断当前路由是否需要进行权限控制
        return next('/login');
    } else {
        next() // 放行
    }
})

router.beforeEach( (to, from, next) => {
    // if (to.path === '/login') return next();
    // const tokenStr = window.sessionStorage.getItem('token');
    // if(!tokenStr) return next('/login');
    next();
})

export default router
